<?php

declare (strict_types=1);


namespace app\common\tool\joinpay;

class Pay extends ApiClient
{
    /**
     * 版本号
     * @var string
     */
    protected string $p0_Version = '2.3';
    /**
     * 商户编号
     * @var string
     */
    protected string $p1_MerchantNo = '888121500006574';

    const SECRET = '4b829c007e994cd3b8afeca9c44424d0';

    public function uniPay($params, $way_pay)
    {
        $data = [
            'p0_Version' => $this->p0_Version,
            'p1_MerchantNo' => $this->p1_MerchantNo,
            'p4_Cur' => 1,
            'qa_TradeMerchantNo' => '777195700663169',
        ];

        if ($way_pay == 'wechat') {
            $data['q9_TransactionModel'] = 'MODEL2';
            $data['q1_FrpCode'] = 'WEIXIN_H5_PLUS';
            $data['q7_AppId'] = 'wx37d65e167f8a7681';
        } else {
            $data['q1_FrpCode'] = 'ALIPAY_H5';
        }
        $data = array_merge($data, $params);
        $content = self::getSignContent($data);
        $sign = md5($content . self::SECRET);
        $data['hmac'] = $sign;

        return $this->post('trade/uniPayApi.action', ['post' => $data]);
    }

    /**
     * 获取签名内容
     * @param array $data
     * @return string
     */
    private static function getSignContent(array $data): string
    {
        list($attrs,) = [[], ksort($data)];
        if (isset($data['hmac'])) unset($data['hmac']);

        foreach ($data as $key => $value) {
            if ($value === '' || is_null($value)) continue;
            $attrs[] = $value;
        }

        return join('', $attrs);
    }

    public static function verify($data): bool
    {
        $content = self::getSignContent($data);
        $sign = md5($content . self::SECRET);
        if ($data['hmac'] != $sign) {
            return false;
        }
        return true;
    }

    /**
     * 提现
     * @param array $params
     */
    public function singlePay(array $params)
    {
        $data = [
            'userNo' => $this->p1_MerchantNo,
            'productCode' => 'BANK_PAY_DAILY_ORDER',
            'requestTime' => date('Y-m-d H:i:s'),
            'merchantOrderNo' => $params['sn'],
            'receiverAccountNoEnc' => $params['bank_number'],
            'receiverNameEnc' => $params['bank_account_name'],
            'receiverAccountType' => '201',
            'paidAmount' => $params['amount'],
            'currency' => '201',
            'isChecked' => '202',
            'paidDesc' => '提现',
            'paidUse' => '205',
            'callbackUrl' => $params['url'],
        ];
        $content = '';
        foreach ($data as $key => $value) {
            $content .= $value;
        }

        $sign = md5($content . self::SECRET);
        $data['hmac'] = $sign;

        return $this->post('payment/pay/singlePay', ['json' => $data]);
    }
}